package top.xzxsrq.fileviewutils.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import top.xzxsrq.common.utils.StringUtilsZX;
import top.xzxsrq.fileviewutils.entity.SysUser;
import top.xzxsrq.fileviewutils.entity.SysUserSearch;
import top.xzxsrq.fileviewutils.entity.SysUserWithRole;
import top.xzxsrq.fileviewutils.mapper.SysUserMapper;
import top.xzxsrq.fileviewutils.service.UserDetailsServiceImpl;
import top.xzxsrq.fileviewutils.service.UserService;
import top.xzxsrq.utils.PathUtils;
import top.xzxsrq.web.utils.AjaxResult;
import top.xzxsrq.web.utils.WebUtils;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public AjaxResult updatePassword(String oldPassword, String newPassword) {
        if (StringUtilsZX.isEmpty(oldPassword)) {
            return AjaxResult.failure("旧密码不能为空");
        }
        if (StringUtilsZX.isEmpty(newPassword)) {
            return AjaxResult.failure("新密码不能为空");
        }
        if (oldPassword.equals(newPassword)) {
            return AjaxResult.failure("新旧密码不能相同");
        }
        SysUserWithRole user = (SysUserWithRole) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = user.getUsername();
        SysUser sysUser = sysUserMapper.selectOneByUsername(username);
        if (sysUser == null) {
            return AjaxResult.failure("用户不存在");
        }
        boolean equals = sysUser.getPassword().equals(passwordEncoder.encode(oldPassword));
        if (equals) {
            sysUserMapper.updatePasswordByUsername(passwordEncoder.encode(newPassword), username);
            return AjaxResult.success("密码更新完成");
        } else {
            return AjaxResult.failure("密码不正确");
        }
    }

    @Override
    public AjaxResult resetPassword(String username, String password) {
        if(StringUtilsZX.isEmpty(username)){
            return AjaxResult.failure("用户名不能为空");
        }
        if(StringUtilsZX.isEmpty(password)){
            return AjaxResult.failure("密码不能为空");
        }
        int i = sysUserMapper.updatePasswordByUsername(passwordEncoder.encode(password), username);
        if(i>0){
            return AjaxResult.success("密码重置完成");
        }
        return AjaxResult.failure("密码重置失败");
    }

    @Override
    public AjaxResult userList(SysUserSearch userSearch, int pageNum, int pageSize) {
        Page<SysUser> sysUserPage = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        SysUserWithRole user = (SysUserWithRole) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(!user.isInitAdmin()) {
            queryWrapper.eq(SysUser::getCreatorId,user.getUserId());
        }
        if(StringUtilsZX.isNotEmpty(userSearch.getUsername())) {
            queryWrapper.like(SysUser::getUsername,userSearch.getUsername());
        }
        Page<SysUser> sysUserPage1 = sysUserMapper.selectPage(sysUserPage, queryWrapper);
        for (SysUser record : sysUserPage1.getRecords()) {
            record.setPassword(null);
            // 路径拉出来就要转成相对路径
            String userpath = record.getUserpath();
            int length = user.getUserpath().length();
            userpath = userpath.substring(length);
            if(!userpath.startsWith("/")) {
                userpath="/"+userpath;
            }
            record.setUserpath(userpath);
        }
        return AjaxResult.success(sysUserPage1);
    }

    private AjaxResult verifyTheUser(SysUser sysUserWithRole) {
        if(StringUtilsZX.isBlank(sysUserWithRole.getUsername())) {
            return AjaxResult.failure("用户名不能为空");
        }
        if(sysUserWithRole.getUsername().length()>255) {
            return AjaxResult.failure("用户名过长：最长255");
        }
        if(StringUtilsZX.isBlank(sysUserWithRole.getUserpath())) {
            return AjaxResult.failure("路径不嫩为空");
        }
        if(sysUserWithRole.getUserpath().length()>255) {
            return AjaxResult.failure("路径过长：最长255");
        }
        if(StringUtilsZX.isBlank(sysUserWithRole.getRoleName())) {
            return AjaxResult.failure("角色不能为空");
        }
        return null;
    }

    @Override
    public AjaxResult addUser(SysUserWithRole sysUserWithRole) {
        if(UserDetailsServiceImpl.adminUserName.equals(sysUserWithRole.getUsername())) {
            return AjaxResult.failure("用户已存在");
        }
        AjaxResult ajaxResult = verifyTheUser(sysUserWithRole);
        if(ajaxResult != null) {
            return ajaxResult;
        }
        String password = sysUserWithRole.getPassword();
        if(StringUtilsZX.isBlank(password)) {
            return AjaxResult.failure("密码不嫩为空");
        }
        if(password.length()>255) {
            return AjaxResult.failure("密码过长：最长255");
        }
        String encode = passwordEncoder.encode(password);
        sysUserWithRole.setPassword(encode);
        sysUserWithRole.setUserId(WebUtils.uuid64());
        SysUserWithRole user = (SysUserWithRole) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        sysUserWithRole.setCreatorId(user.getUserId());
        String userpath = sysUserWithRole.getUserpath();
        // 往库里面存就是绝对路径
        sysUserWithRole.setUserpath(PathUtils.pathResolve(user.getUserpath(),userpath));
        sysUserMapper.insert(sysUserWithRole);
        return AjaxResult.success("添加完成");
    }

    @Override
    public AjaxResult delUser(String userId) {
        sysUserMapper.deleteById(userId);
        return AjaxResult.success("删除完成");
    }

    @Override
    public AjaxResult resetInitPassword(String newPassword) {
        UserDetailsServiceImpl.adminPassword = newPassword;
        return AjaxResult.success("重置完成");
    }

    @Override
    public AjaxResult getUserById(String userId) {
        SysUser sysUser = sysUserMapper.selectById(userId);
        sysUser.setPassword(null);
        return AjaxResult.success(sysUser);
    }

    @Override
    public AjaxResult updateUser(SysUser sysUser) {
        AjaxResult ajaxResult = verifyTheUser(sysUser);
        if(ajaxResult != null) {
            return ajaxResult;
        }
        SysUserWithRole user = (SysUserWithRole) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userpath = sysUser.getUserpath();
        // 往库里面存就是绝对路径
        sysUser.setUserpath(PathUtils.pathResolve(user.getUserpath(),userpath));
        int i = sysUserMapper.updateById(sysUser);
        return AjaxResult.success("更新完成");
    }

    @Override
    public AjaxResult updateUserSysConfig(String userSysConfig) {
        SysUserWithRole user = (SysUserWithRole) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(user.isInitAdmin()){
            UserDetailsServiceImpl.updateAdminUserSysConfig(userSysConfig);
        } else{
            sysUserMapper.updateUserSysConfigByUserId(userSysConfig,user.getUserId());
        }
        return AjaxResult.success("更新完成");
    }

    @Override
    public AjaxResult getInfo() {
        SysUserWithRole user = (SysUserWithRole) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        user.setPassword(null);
        if(user.isInitAdmin()) {
            user.setUserSysConfig(UserDetailsServiceImpl.adminUserSysConfig);
        } else {
            String sysConfigByUserId = sysUserMapper.selectUserSysConfigByUserId(user.getUserId());
            user.setUserSysConfig(sysConfigByUserId);
        }
        return AjaxResult.success(user);
    }
}
